package io;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class MyclassLoader extends ClassLoader{
	private String classPath;
	
	public MyclassLoader(String classPath){
		this.classPath=classPath;
	}
	
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		String packageName="";
		
		if(packageName.startsWith(name)){
			byte[]classData=GetData(name);
			if(classData==null){
				throw new ClassNotFoundException();
			}else{
				return defineClass(name, classData, 0, classData.length);
			}
		}else{
			return super.loadClass(name);
		}
	}
	
	private byte[] GetData(String name) {
		String path=classPath+File.separatorChar+name.replace('.', File.separatorChar)+".class";
		try{
			InputStream iStream=new  FileInputStream(path);
			ByteArrayOutputStream bos=new ByteArrayOutputStream();
			byte[]buffer=new byte[2048];
			int num=0;
			while((num=iStream.read(buffer))!=-1){
				bos.write(buffer,0,num);
			}
			return bos.toByteArray();
		}catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
